package com.waterworld.watch.home.fragment;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.waterworld.watch.R;
import com.waterworld.watch.call.ui.SelectActivity;
import com.waterworld.watch.common.bean.UserInfoBean;
import com.waterworld.watch.common.bean.WatchUserInfoBean;
import com.waterworld.watch.common.customview.MyPtrHeaderView;
import com.waterworld.watch.common.net.BaseObserverListener;
import com.waterworld.watch.common.net.BaseResultBean;
import com.waterworld.watch.common.util.ToastUtils;
import com.waterworld.watch.home.activity.HomePagerActivity;
import com.waterworld.watch.home.activity.SkillManagerActivity;
import com.waterworld.watch.home.activity.SkillContactListActivity;
import com.waterworld.watch.home.activity.SkillRemoteShotActivity;
import com.waterworld.watch.home.activity.SkillSingleListenerActivity;
import com.waterworld.watch.home.activity.SkillSportActivity;
import com.waterworld.watch.home.activity.SkillCurriculumActivity;
import com.waterworld.watch.home.adapter.HomeSkillAdapter;
import com.waterworld.watch.home.bean.SkillManagerBean;
import com.waterworld.watch.home.constant.SkillConstant;
import com.waterworld.watch.home.event.FunctionsEvent;
import com.waterworld.watch.home.event.WatchUserInfoEvent;
import com.waterworld.watch.home.interfaces.IHomeManager;
import com.waterworld.watch.home.manager.HomeManager;
import com.waterworld.watch.login.event.AutoLoginEvent;
import com.waterworld.watch.mine.activity.IntimateActivity;
import com.waterworld.watch.mine.activity.NotificationActivity;
import com.waterworld.watch.mine.activity.TimingActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import in.srain.cube.views.ptr.PtrClassicDefaultHeader;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.header.MaterialHeader;
import in.srain.cube.views.ptr.header.StoreHouseHeader;
import in.srain.cube.views.ptr.util.PtrLocalDisplay;

public class HomeFragment extends Fragment {

    @BindView(R.id.rv_skill_list)
    RecyclerView rv_skill_list;

    @BindView(R.id.ptr_frame)
    PtrFrameLayout ptr_frame;

    private HomePagerActivity parent;
    private HomeSkillAdapter skillAdapter;
    private List<SkillManagerBean> skillList = new ArrayList<>();
    //打电话权限
    private static final int REQ_CODE_PERMISSION = 0x02;
    //录音权限
    private static final int REQ_CODE_RECORD = 0x03;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        parent = (HomePagerActivity) getActivity();
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.fragment_home,container,false);
        ButterKnife.bind(this,view);
        EventBus.getDefault().register(this);
        initView();
        return view;
    }


    private void initView() {
        MyPtrHeaderView header = new MyPtrHeaderView(parent);
        ptr_frame.setKeepHeaderWhenRefresh(true);
        ptr_frame.setHeaderView(header);
        ptr_frame.addPtrUIHandler(header);
        ptr_frame.disableWhenHorizontalMove(true);
        PtrHandler handler = new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                ptr_frame.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        EventBus.getDefault().post(new AutoLoginEvent(1,null));
                    }
                }, 500);
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                //解决RecycleView和PtrFrameLayout滑动冲突问题
                return !rv_skill_list.canScrollVertically(-1);
            }
        };
        ptr_frame.setPtrHandler(handler);
    }
    private void initData() {
        skillList.clear();
        if(WatchUserInfoBean.getInstance().getWatchUserInfo().getFunctionSign() != null){
            String[] functions = WatchUserInfoBean.getInstance().getWatchUserInfo().getFunctionSign().split(",");
            operationFunction(functions, skillList);
        }
        if (UserInfoBean.getInstance().getWatchUser().getUserRole().equals(0)) {
            //仅管理员可修改
            skillList.add(new SkillManagerBean(getString(R.string.add_function), getResources().getDrawable(R.drawable.ic_skill_add)));
        }
        skillAdapter = new HomeSkillAdapter(parent, skillList);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(parent);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rv_skill_list.setLayoutManager(new GridLayoutManager(parent, 3));
        rv_skill_list.setAdapter(skillAdapter);
        skillClick();
    }

    private void operationFunction(String[] arr1, List<SkillManagerBean> arr2) {
        for (String function : arr1) {
            if (function.equals(SkillConstant.ADDRESS_BOOK)) {
                arr2.add(new SkillManagerBean(getString(R.string.address_book), getResources().getDrawable(R.drawable.ic_skill_contact)));
            } else if (function.equals(SkillConstant.BAN_CLASSES)){
                arr2.add(new SkillManagerBean(getString(R.string.ban_class),getResources().getDrawable(R.drawable.ic_skill_ban_class)));
            }else if (function.equals(SkillConstant.CURRICULUM)){
                arr2.add(new SkillManagerBean(getString(R.string.curriculum),getResources().getDrawable(R.drawable.ic_skill_curriculum)));
            }else if (function.equals(SkillConstant.INTIMATE_SET)){
                arr2.add(new SkillManagerBean(getString(R.string.intimate_set),getResources().getDrawable(R.drawable.ic_skill_intimate)));
            }else if (function.equals(SkillConstant.MSG_NOTICE)){
                arr2.add(new SkillManagerBean(getString(R.string.msg_notice),getResources().getDrawable(R.drawable.ic_skill_message)));
            }else if (function.equals(SkillConstant.ONE_WAY_LISTEN)){
                arr2.add(new SkillManagerBean(getString(R.string.one_way_listen),getResources().getDrawable(R.drawable.ic_skill_listener)));
            }else if (function.equals(SkillConstant.PHONE)){
                arr2.add(new SkillManagerBean(getString(R.string.phone),getResources().getDrawable(R.drawable.ic_skill_phone)));
            }else if (function.equals(SkillConstant.REMOTE_SHUTDOWN)){
                arr2.add(new SkillManagerBean(getString(R.string.remote_shutdown),getResources().getDrawable(R.drawable.ic_skill_switch)));
            }else if (function.equals(SkillConstant.SCHEDULE_REMINDER)){
                arr2.add(new SkillManagerBean(getString(R.string.schedule_reminder),getResources().getDrawable(R.drawable.ic_skill_ban_class)));
            }else if (function.equals(SkillConstant.SPORTS_COUNT)){
                arr2.add(new SkillManagerBean(getString(R.string.sport_count),getResources().getDrawable(R.drawable.ic_skill_sports)));
            }else if (function.equals(SkillConstant.TIMED_SHUTDOWN)){
                arr2.add(new SkillManagerBean(getString(R.string.timed_shutdown),getResources().getDrawable(R.drawable.ic_skill_alarm)));
            }else if (function.equals(SkillConstant.REMOTE_CAMARA)){
                arr2.add(new SkillManagerBean(getString(R.string.remote_shot),getResources().getDrawable(R.drawable.ic_skill_camera)));
            }else if (function.equals(SkillConstant.SOS_CONTACT)){
                arr2.add(new SkillManagerBean(getString(R.string.sos_contact),getResources().getDrawable(R.drawable.ic_skill_sos)));
            }else if (function.equals(SkillConstant.VIDEO_CHAT)){
                arr2.add(new SkillManagerBean(getString(R.string.video_chat),getResources().getDrawable(R.drawable.ic_skill_video_chat)));
            }
        }
    }

    private void skillClick() {
        skillAdapter.setAddSkillClick(new HomeSkillAdapter.SkillClick() {
            @Override
            public void skillClick(View view, int position) {
                if (UserInfoBean.getInstance().getWatchUser().getUserRole().equals(0)) {
                    if (skillAdapter.getItemCount() != 0 && skillAdapter.getItemCount() - 1 == position) {
                        startActivity(new Intent(parent, SkillManagerActivity.class));
                    }
                }
                if (skillAdapter.getMData().get(position).getSkillName().equals(getString(R.string.phone))) {
                    if (ContextCompat.checkSelfPermission(parent, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(parent, new String[]{Manifest.permission.CALL_PHONE}, REQ_CODE_PERMISSION);
                    } else {
                        call(WatchUserInfoBean.getInstance().getWatchUserInfo().getPhone());
                    }
                } else if (skillAdapter.getMData().get(position).getSkillName().equals(getString(R.string.address_book))) {
                    startActivity(new Intent(parent, SkillContactListActivity.class));
                } else if (skillAdapter.getMData().get(position).getSkillName().equals(getString(R.string.msg_notice))) {
                    startActivity(new Intent(parent, NotificationActivity.class));
                } else if (skillAdapter.getMData().get(position).getSkillName().equals(getString(R.string.intimate_set))) {
                    startActivity(new Intent(parent, IntimateActivity.class));
                } else if (skillAdapter.getMData().get(position).getSkillName().equals(getString(R.string.timed_shutdown))) {
                    startActivity(new Intent(parent, TimingActivity.class));
                } else if (skillAdapter.getMData().get(position).getSkillName().equals(getString(R.string.sport_count))) {
                    startActivity(new Intent(parent, SkillSportActivity.class));
                } else if (skillAdapter.getMData().get(position).getSkillName().equals(getString(R.string.one_way_listen))) {
                    startActivity(new Intent(parent, SkillSingleListenerActivity.class));
                } else if (skillAdapter.getMData().get(position).getSkillName().equals(getString(R.string.curriculum))) {
                    startActivity(new Intent(parent, SkillCurriculumActivity.class));
                } else if (skillAdapter.getMData().get(position).getSkillName().equals(getString(R.string.remote_shot))) {
                    startActivity(new Intent(parent, SkillRemoteShotActivity.class));
                } else if (skillAdapter.getMData().get(position).getSkillName().equals(getString(R.string.video_chat))) {
                    if (ContextCompat.checkSelfPermission(parent, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(parent, new String[]{Manifest.permission.RECORD_AUDIO,Manifest.permission.CAMERA}, REQ_CODE_RECORD);
                    } else {
                        startActivity(new Intent(parent, SelectActivity.class));

                    }
                }
            }
        });
    }


    private void call(String number) {
        Intent intent = new Intent(Intent.ACTION_CALL);
        Uri data = Uri.parse("tel:" + number);
        intent.setData(data);
        startActivity(intent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQ_CODE_PERMISSION:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    call(WatchUserInfoBean.getInstance().getWatchUserInfo().getPhone());
                } else {
                    ToastUtils.showLong(parent, getString(R.string.have_to_agree_premissions));
                }
                break;
            case REQ_CODE_RECORD:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    startActivity(new Intent(parent, SelectActivity.class));
                } else {
                    ToastUtils.showLong(parent, getString(R.string.have_to_agree_premissions));
                }
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateFunctions(FunctionsEvent functionsEvent){
        skillList.clear();
        operationFunction(functionsEvent.getFunctions(),skillList);
        skillList.add(new SkillManagerBean(getString(R.string.add_function), getResources().getDrawable(R.drawable.ic_skill_add)));
        skillAdapter.notifyDataSetChanged();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getWatchUserInfo(WatchUserInfoEvent event) {
        if (event.isLoad()) {
            initData();
            ptr_frame.refreshComplete();
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
